import wtforms
from exts import db
from wtforms.validators import Email, length, EqualTo
from models import UserModel,EmailCaptchaModel
class RegisterForm(wtforms.Form):
    email = wtforms.StringField(validators=[Email(message='邮箱格式不正确!')])
    captcha = wtforms.StringField(validators=[wtforms.validators.length(min=4, max=4, message='验证码长度不正确!')])
    username = wtforms.StringField(validators=[wtforms.validators.length(min=3, max=20, message='用户名长度不正确!')])
    password = wtforms.StringField(validators=[wtforms.validators.length(min=6, max=20, message='密码长度不正确!')])
    password_confirm = wtforms.StringField(validators=["password"])

    def validate_email(self, field):
        email = field.data
        user = UserModel.query.filter_by(email=email).first()
        if user:
            raise wtforms.ValidationError(message='邮箱已经存在!')

    def validate_captcha(self, field):
        captcha = field.data
        email = self.email.data
        captcha_model = EmailCaptchaModel.query.filter_by(email=email, captcha=captcha).first()
        if not captcha_model:
            raise wtforms.ValidationError(message='邮箱或验证码错误!')
        else:
            db.session.delete(captcha_model)
            db.session.commit()
